package com.bdd.config;



import com.bdd.entity.User;
import com.bdd.mapper.UserDAO;
import com.bdd.service.UserService;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;


public class UserRealm extends AuthorizingRealm {

    @Resource
    UserDAO userDAO;

    @Resource
    UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取用户名
        User user = (User) principalCollection.getPrimaryPrincipal();
        String username = user.getUsername();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //给admin设置角色(应该从数据库表中获取)
        String roleName = userService.getUserRolesByUsername(username);
        authorizationInfo.addRole(roleName);
        //给用户设置权限
//        authorizationInfo.setStringPermissions();
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = (String) token.getPrincipal();
        String password = new String(token.getPassword());
        User user = userDAO.selectByUsernameAndPassword(username, password);
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password) || ObjectUtils.isEmpty(user)) {
            throw new IllegalArgumentException("账号或密码错误");
        }

        if (username.equals(user.getUsername())) {
            return new SimpleAuthenticationInfo(user, user.getPassword(), this.getName());
        }

        return null;
    }
}

